<template>
    <div class="home" style=" padding: 10px">
        <!--  功能区域  -->
        <div class="flex-bar">
            <!--  搜索区域  -->
            <div style="margin: 10px 0">
                <el-input v-model="search" placeholder="请输入要查询的房屋地址" style="width: 300px; margin-right: 5px" clearable
                          @keyup.enter="load"></el-input>
                <el-button type="primary" style="margin-right:20px; margin-left: 5px" @click="load">查询</el-button>
            </div>
            <div style="margin: 10px 0">
                <el-button type="primary" @click="add" v-if="user.role === 0 || user.role === 1">新增</el-button>
            </div>
        </div>
        <el-table
                :data="tableData"
                border
                stripe
                style="width: 100%">
            <el-table-column
                    prop="id"
                    label="ID"
                    v-if="this.user.role === 0"
                    sortable/>
            <el-table-column
                    prop="name"
                    label="房主姓名"
                    v-if="this.user.role === 0"/>
            <el-table-column
                    prop="houseAddress"
                    label="房屋地址"/>
            <el-table-column
                    prop="type"
                    label="房屋类型"/>
            <el-table-column
                    prop="suitableNumber"
                    label="可住人数"/>
            <el-table-column
                    prop="rent"
                    label="月租金"/>
            <el-table-column
                    prop="photo"
                    label="房屋照片">
                <template #default="scope">
                    <el-image
                            style="width: 100px"
                            :src="scope.row.photo"
                            :preview-src-list="[scope.row.photo]">
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column
                    v-if="user.role === 2"
                    label="操作">
                <template #default="scope">
                    <el-popconfirm title="确认提交租房申请吗？" @confirm="wantRent(scope.row.id,scope.row.houseAddress)">
                        <template #reference>
                            <el-button size="mini" type="success">有意向租房</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
            <el-table-column
                    v-if="user.role === 1 || user.role === 0"
                    label="操作">
                <template #default="scope">
                    <el-button @click="handleEdit(scope.row)" size="mini">编辑</el-button>
                    <el-popconfirm title="确认删除吗？" @confirm="handleDelete(scope.row.id)">
                        <template #reference>
                            <el-button type="danger" size="mini">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!--  分页模块  -->
        <div style="margin: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <!--  二层弹窗  -->
        <el-dialog
                title="请支付押金"
                v-model="moneyVis"
                width="600px">
            <el-form :model="form" label-width="120px">
                <el-form-item label="应缴押金">
                    {{ money }}
                </el-form-item>
                <el-form-item label="付款码">
                    <el-image
                            style="height: 300px"
                            :src="url"
                            :preview-src-list="[url]">
                    </el-image>
                </el-form-item>
                <el-form-item label="支付方式">
                    <el-radio-group v-model="radioPay">
                        <el-radio @click="zfb" label="支付宝">支付宝</el-radio>
                        <el-radio @click="wx" label="微信支付">微信支付</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
          <span class="dialog-footer">
            <el-button @click="moneyVis = false">取 消</el-button>
            <el-button type="primary" @click="alreadyPay">我已缴费</el-button>
          </span>
            </template>
        </el-dialog>

        <!--  一层弹窗  -->
        <el-dialog
                :title="title"
                v-model="dialogVisible"
                width="600px">
            <el-form :model="form" label-width="120px" :rules="rules">
                <el-form-item label="房屋地址" prop="houseAddress">
                    <el-input v-model="form.houseAddress" style="width: 80%;"></el-input>
                </el-form-item>
                <el-form-item label="房屋类型" prop="type">
                    <el-input v-model="form.type" style="width: 80%;"></el-input>
                </el-form-item>
                <el-form-item label="可住人数" prop="suitableNumber">
                    <el-input v-model="form.suitableNumber" style="width: 80%;"></el-input>
                </el-form-item>
                <el-form-item label="月租金" prop="rent">
                    <el-input v-model="form.rent" style="width: 80%;"></el-input>
                </el-form-item>
                <el-form-item label="房屋照片">
                    <el-upload ref="upload" action="http://localhost:9090/files/upload"
                               :on-success="filesUploadSuccess">
                        <el-button type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </span>
            </template>
        </el-dialog>
    </div>


</template>

<style>
    .flex-bar {
        display: flex;
        flex-direction: row;
        align-items: center;
    }
</style>

<script>

    import request from "../utils/request";

    export default {
        name: 'House',
        components: {},
        data() {
            return {
                rules: {
                    houseAddress: [
                        {required: true, message: '请输入房屋地址', trigger: 'blur'},
                    ],
                    type: [
                        {required: true, message: '请输入房屋类型', trigger: 'blur'},
                    ],
                    suitableNumber: [
                        {required: true, message: '请输入可住人数', trigger: 'blur'},
                    ],
                    rent: [
                        {required: true, message: '请输入月租金', trigger: 'blur'},
                    ],
                },
                form: {
                    rent: 0,
                },
                formWantRent: {},
                formMeeting: {},
                dialogVisible: false,
                moneyVis: false,
                search: '',
                currentPage: 1,
                pageSize: 10,
                total: 0,
                tableData: [],
                user: {},
                title: '',
                money: 0,
                radioPay: '支付宝',
                url: require('@/assets/img/zfb.jpg'),
            }
        },
        created() {
            let ownerStr = sessionStorage.getItem("user") || "{}";
            this.user = JSON.parse(ownerStr);

            //请求服务端，确认当前登录用户的合法信息
            request.get("/user/" + this.user.id).then(res => {
                if (res.code === '0') {
                    this.user = res.data;
                }
            });
            this.load();
        },
        methods: {
            alreadyPay() {
                request.post("/house", this.form).then(res => {
                    console.log(res);
                    if (res.code == '0') {
                        this.$message({
                            type: "success",
                            message: "新增成功"
                        });
                        this.load();   //刷新表格的数据
                        this.moneyVis = false;  //关闭弹窗
                    } else {
                        this.$message({
                            type: "error",
                            message: res.msg
                        })
                    }
                });
            },
            zfb() {     //若点击支付宝按钮，则将付款码切换为支付宝付款码
                this.radioPay = "支付宝";
                this.url = require('@/assets/img/zfb.jpg');
            },
            wx() {     //若点击微信支付按钮，则将付款码切换为微信付款码
                this.radioPay = "微信支付";
                this.url = require('@/assets/img/wx.png');
            },
            wantRent(id,address) {    //点击想要租房，则将申请信息分别添加到wantrent表和meeting表中
                //将申请信息添加到wantrent表中
                this.formWantRent.houseId = id;
                this.formWantRent.tenantId = this.user.id;
                request.post("/wantRent", this.formWantRent).then(res => {
                    if (res.code == '0') {

                    } else {
                        this.$message({
                            type: "error",
                            message: res.msg
                        });
                        return;
                    }
                });
                //将申请信息添加到meeting表中
                this.formMeeting.houseId = id;
                this.formMeeting.tenantId = this.user.id;
                this.formMeeting.meetTime = new Date();
                this.formMeeting.meetAddress = address;
                this.formMeeting.ownerConfirm = -1;
                this.formMeeting.tenantConfirm = -1;
                request.post("/meeting", this.formMeeting).then(res => {
                    console.log(res);
                    if (res.code == '0') {
                        this.$message({
                            type: "success",
                            message: "申请租房成功"
                        });
                        this.load();   //刷新表格的数据
                    } else {
                        this.$message({
                            type: "error",
                            message: res.msg
                        })
                    }
                });
            },
            filesUploadSuccess(res) {   //确认上传图片的地址
                console.log(res);
                this.form.photo = res.data;
            },
            load() {      //登陆或进行任何数据操作后，都应该调用load方法刷新网页
                if (this.user.role === 1) {    //登陆的是房主，则看到自己的房屋的信息
                    request.get("/house/ownerHouse", {
                        params: {
                            pageNum: this.currentPage,
                            pageSize: this.pageSize,
                            search: this.search,
                            ownerId: this.user.id,
                        }
                    }).then(res => {
                        console.log(res);
                        this.tableData = res.data.records;
                        this.total = res.data.total;
                    })
                } else if (this.user.role === 0) {  //登陆的是管理员，则能看到所有房屋的信息，包括房主的姓名
                    request.get("/house", {
                        params: {
                            pageNum: this.currentPage,
                            pageSize: this.pageSize,
                            search: this.search
                        }
                    }).then(res => {
                        console.log(res)
                        this.tableData = res.data.records;
                        this.total = res.data.total;
                    })
                } else {  //登陆的是租客，则能看到所有待出租且未被自己申请的房屋
                    request.get("/house/findNotRent", {
                        params: {
                            pageNum: this.currentPage,
                            pageSize: this.pageSize,
                            search: this.search,
                            id: this.user.id
                        }
                    }).then(res => {
                        console.log(res)
                        this.tableData = res.data.records;
                        this.total = res.data.total;
                    })
                }
            },
            add() {    //点击“新增”按钮
                this.dialogVisible = true;
                this.title = '新增房屋';
                this.form = {};
                if (this.$refs['upload']) {
                    this.$refs['upload'].clearFiles();  //清除历史文件列表
                }
            },
            save() {    //点击一层弹窗的确认按钮，则进入二层弹窗
                if (this.form.id) {  //更新
                    this.form.ownerId = this.user.id;
                    request.put("/house", this.form).then(res => {
                        console.log(res);
                        if (res.code == '0') {
                            this.$message({
                                type: "success",
                                message: "更新成功"
                            });
                            this.load();   //刷新表格的数据
                            this.dialogVisible = false;  //关闭弹窗
                        } else {
                            this.$message({
                                type: "error",
                                message: res.msg
                            })
                        }
                    });
                } else {    //新增
                    this.form.ownerId = this.user.id;
                    this.form.isAble = 1;
                    this.dialogVisible = false;  //关闭一层弹窗
                    if (this.form.houseAddress != null && this.form.type != null && this.form.suitableNumber != null && this.form.rent != null){
                        this.moneyVis = true;        //打开二层弹窗
                        this.money = this.form.rent * 2;  //设置押金为月租金的两倍
                    }
                    else {
                        this.$message({
                            type: "error",
                            message: "请填写房屋的所有信息！"
                        });
                        this.dialogVisible = true;
                    }
                }
            },
            handleEdit(row) {
                this.form = JSON.parse(JSON.stringify(row));
                this.title = '编辑房屋信息';
                this.dialogVisible = true;
                this.$nextTick(() => {
                    if (this.$refs['upload']) {
                        this.$refs['upload'].clearFiles();  //清除历史文件列表
                    }
                })
            },
            handleDelete(id) {
                console.log(id);
                request.delete("/house/" + id).then(res => {
                    if (res.code == '0') {
                        this.$message({
                            type: "success",
                            message: "删除成功"
                        });
                    } else {
                        this.$message({
                            type: "error",
                            message: res.msg
                        })
                    }
                    this.load();
                })
            },
            handleSizeChange(pageSize) {    //改变当前每页个数触发
                this.pageSize = pageSize;
                this.load();
            },
            handleCurrentChange(pageNum) {  //改变当前页码触发
                this.currentPage = pageNum;
                this.load();
            }
        }
    }
</script>